package mws;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.Map;

import static mws.ClientHandler.ASYNC;
import static mws.ClientHandler.buildMsg;

public class MapperClient {
    private static final Logger log = LoggerFactory.getLogger(MapperClient.class);
    // 服务器地址
    private final String host;
    // 服务器端口
    private final int port;

    @Getter
    private Channel channel;

    @Setter
    private MapContext mapContext;

    public MapperClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws InterruptedException {
        // 客户端事件循环组，通常只需要一个
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // Bootstrap 是 Netty 客户端的启动辅助类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    // 设置使用 NIO 通道
                    .channel(NioSocketChannel.class)
                    // 设置连接超时时间
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                    // 设置 TCP _NODELAY 选项，禁用 Nagle 算法
                    // 设置通道初始化器，用于配置新连接的 ChannelPipeline
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 添加处理器到通道的 pipeline 中
                            ch.pipeline()
                                    // 字符串解码器
                                    .addLast(new StringDecoder())
                                    // 字符串编码器
                                    .addLast(new StringEncoder())
                                    // 自定义客户端处理器
                                    .addLast(new ClientHandler());
                        }
                    });
// 这是一个非常好的配置，请使用它
            bootstrap.option(ChannelOption.TCP_NODELAY, true)    // 禁用 Nagle 算法，降低延迟
                    .option(ChannelOption.SO_KEEPALIVE, true)   // 启用保活机制，增强可靠性
                    .option(ChannelOption.SO_SNDBUF, 65536)     // 增大发送缓冲区，提高吞吐
                    .option(ChannelOption.SO_RCVBUF, 65536);    // 增大接收缓冲区，提高吞吐
            // 连接服务器，同步等待连接完成
            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("客户端已连接到服务器: " + host + ":" + port);

            // 获取通道对象
            Channel channel = future.channel();
            this.channel = channel;
            // 等待通道关闭z
            channel.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {

                    // 通道关闭后执行的操作
                    log.info("ChannelClose");
                    group.shutdownGracefully();
                    // 关闭 MapContext
                    if (mapContext != null) {
                        mapContext.close();
                    }
                }
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public void sendAsync(Map<String,String> data) {
        sendKennel(ASYNC, data);
    }

    public void sendSync(Map<String,String> data) {
        sendKennel(ClientHandler.SYNC, data);
    }

    public void sendKennel(int type, Map data) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(buildMsg(type, data)).addListener(future -> {
                if (future.isSuccess()) {
                    log.info("发送消息成功");
                } else {
                    log.error("发送消息失败", future.cause());  // todo 这里 有没有容错
                }
            });
        }
    }

}
